﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace chessLogic
{
    public class PGNExportParser
    {
        public void WriteFile(string filePath, List<Game> games)
        {
            string PGNString = ParseToPGNFormat(games);
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.Write(PGNString);
            }
        }
        public string ParseToPGNFormat(List<Game> games)
        {
            string parsedToPGN = "";
            foreach (Game game in games)
            {
                parsedToPGN += ParseTag(game);
                parsedToPGN += ParseMoves(game);
            }
            return parsedToPGN;
        }
        public string ParseTag(Game game)
        {
            string tagsGameInString = "\r\n";
            tagsGameInString += "[Event \"" + game.Event + "\"]\r\n";
            tagsGameInString += "[Site \"" + game.Site + "\"]\r\n";
            tagsGameInString += "[Date \"" + game.Date + "\"]\r\n";
            tagsGameInString += "[Round \"" + game.Round + "\"]\r\n";
            tagsGameInString += "[White \"" + game.White + "\"]\r\n";
            tagsGameInString += "[Black \"" + game.Black + "\"]\r\n";
            tagsGameInString += "[Result \"" + game.Result + "\"]\r\n";
            tagsGameInString += "[ECO \"" + game.ECO + "\"]\r\n";
            return tagsGameInString;
        }
        public string ParseMoves(Game game)
        {
            string movesGameInString = "\r\n";
            List<string> temp = new List<string>();
            int moveNum = 0;
            for (int i = 0; i < game.Moves.Count; i++)
            {
                if (i % 2 == 0)
                {
                    moveNum++;
                    string tempString = moveNum + "." + game.Moves[i] + " ";
                    if (i + 1 < game.Moves.Count)
                        tempString += game.Moves[i + 1] + " ";
                    temp.Add(tempString);
                }
            }
            int numLine = 0;
            foreach(string tempString in temp)
            {
                if (numLine == 3)
                {
                    movesGameInString += tempString + "\r\n";
                    numLine = 0;
                }
                else
                {
                    movesGameInString += tempString;
                    numLine++;
                }
            }
            movesGameInString += game.Result + "\r\n";
            return movesGameInString;
        }
    }
}
